package com.payment.ktb.activity.main1;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;

import com.android.volley.VolleyError;
import com.payment.ktb.Interface.HttpCallbackListener;
import com.payment.ktb.R;
import com.payment.ktb.activity.BaseActivity;
import com.payment.ktb.constants.Constants;
import com.payment.ktb.constants.ConstantsPay;
import com.payment.ktb.constants.ConstantsUser;
import com.payment.ktb.constants.HttpActions;
import com.payment.ktb.constants.HttpUrls;
import com.payment.ktb.utils.AlertDialogUtils;
import com.payment.ktb.utils.HttpUtils;
import com.payment.ktb.utils.Md5Utils;
import com.payment.ktb.utils.SharedPreferencesUtils;
import com.payment.ktb.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by syd on 2016/6/10.
 */
public class AddBankcardActivity extends BaseActivity {

    private int MY_SCAN_REQUEST_CODE = 100; // arbitrary int
    @BindView(R.id.et_addbankcard_cardno)
    EditText et_addbankcard_cardno;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addbankcard);
        ButterKnife.bind(this);
        et_addbankcard_cardno.addTextChangedListener(textWatcher);
        initTitle("添加银行卡");
    }



    @OnClick({R.id.btn_addbankcard_confirm,R.id.iv_addbankcard_takephoto})
    public void clickEvent(View view) {

        switch (view.getId()) {

            //提交信用卡
            case R.id.btn_addbankcard_confirm:


                if (!TextUtils.isEmpty(et_addbankcard_cardno.getText().toString().trim())) {
                    ConstantsPay.bankNo = et_addbankcard_cardno.getText().toString().trim().replace(" ","");
                    submit();
                } else {
                    ToastUtils.showToast("请输入正确的银行卡!");
                }

                break;


//            //拍照识别信用卡
//            case R.id.iv_addbankcard_takephoto:
//
//                Intent scanIntent = new Intent(this, CardIOActivity.class);
//                // MY_SCAN_REQUEST_CODE is arbitrary and is only used within this activity.
//                startActivityForResult(scanIntent, MY_SCAN_REQUEST_CODE);
//
//                break;


        }

    }





//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//
//        if (requestCode == MY_SCAN_REQUEST_CODE) {
//            if (data != null && data.hasExtra(CardIOActivity.EXTRA_SCAN_RESULT)) {
//                CreditCard scanResult = data.getParcelableExtra(CardIOActivity.EXTRA_SCAN_RESULT);
//                et_addbankcard_cardno.setText(scanResult.cardNumber);
//            }
//        }
//    }










    /**
     *
     */
    private void submit() {

            progressDialogUtils.showProgress();

            //构造传输参数
            String orderNo = ConstantsPay.orderNo;
            String bankNo = ConstantsPay.bankNo;
            String token = SharedPreferencesUtils.getString(ConstantsUser.userToken);
            String sign = Md5Utils.md5Hex(bankNo +orderNo + SharedPreferencesUtils.getString(ConstantsUser.userKey));



            //将参数放入map中
            HashMap<String, String> map = new HashMap<String,String>();

            map.put("orderNo",orderNo);
            map.put("bankNo",bankNo);
            map.put("token",token);
            map.put("sign",sign);

            //向服务器发送请求
            HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.nocardOrderBankState, map, mQueue, new HttpCallbackListener() {
                @Override
                public void onFinish(String response) {

                    progressDialogUtils.dismissProgress();

                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String code = jsonObject.optString("code");
                        if (Constants.NORMAL_CODE.equals(code)) {

                            ConstantsPay.selfFlg = jsonObject.optString("selfFlg");
                            ConstantsPay.bankCardType = jsonObject.optString("bankCardType");
                            ConstantsPay.bankCardName = jsonObject.optString("bankCardName");
                            ConstantsPay.bankCardIcon = jsonObject.optString("bankCardIcon");
                            if (getIntent().getStringExtra("fromPersionalInfo") != null && getIntent().getStringExtra("fromPersionalInfo").equals("fromPersionalInfo")) {
                                startActivity(ActivationActivity.class);
                            } else if ("1".equals(ConstantsPay.selfFlg)) {
                                startActivity(NocardOrderSubmitBindActivity.class);
                            } else {
                                startActivity(NocardOrderSubmitNobindActivity.class);
                            }
                        } else {

                            AlertDialogUtils.showAlertDialog(mContext, jsonObject.optString("msg"));

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                    }
                }

                @Override
                public void onError(VolleyError volleyError) {

                    progressDialogUtils.dismissProgress();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.fail_to_connect_server));
                }
            });

    }


    private TextWatcher textWatcher = new TextWatcher() {

        int lastLength = 0;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String etValues = s.toString();

            if (lastLength < etValues.length()) {
                etValues = clearSpace(etValues);
                etValues = insertSpace(etValues);
                lastLength = etValues.length();
                et_addbankcard_cardno.setText(etValues);
                et_addbankcard_cardno.setSelection(etValues.length());

            }else {
                lastLength = etValues.length();
            }
        }
        //清除卡号中的空格
        private String clearSpace(String s) {

            return  s.replace(" ","");

        }
        //插入卡号中的空格
        private String insertSpace(String s) {

            if (s.length() > 4) {
                return  s.substring(0,4) + " " + insertSpace(s.substring(4,s.length()));
            }
            return s;
        }


    };



}
